<template>
  <div class="page-stock-purchases-order-list mod-order-order">
    <div class="search-bar">
      <el-form
        :inline="true"
        :model="dataForm"
        label-width="auto"

        @submit.prevent
        @keyup.enter="getDataList(page)"
      >
        <div class="input-row">
          <el-form-item :label="$t('purchase.order.purchaseNumber') + ':'">
            <el-input
              v-model="params.purchaseNumber"
              :placeholder="$t('purchase.order.purchaseNumber')"
              clearable
              :maxlength="50"
            />
          </el-form-item>
          <el-form-item :label="$t('purchase.order.supplier') + ':'">
            <el-input
              v-model="params.supplierName"
              :maxlength="50"
              :placeholder="$t('purchase.order.supplier')"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t("order.query") }}
            </div>
            <div
              class="default-btn"
              @click="clear()"
            >
              {{ $t("shop.resetMap") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('purchase:purchaseOrder:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate(0)"
        >
          {{ $t('crud.addBtn') }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con">
        <!-- 导航 -->
        <el-tabs
          v-model="activeName"
          @tab-click="selectNav"
        >
          <el-tab-pane
            name="0"
            :label="$t('time.a')"
          />
          <el-tab-pane
            name="1"
            :label="$t('purchase.order.voided')"
          />
          <el-tab-pane
            name="2"
            :label="$t('purchase.order.warehoused')"
          />
          <el-tab-pane
            name="3"
            :label="$t('purchase.order.partiallyComplete')"
          />
          <el-tab-pane
            name="4"
            :label="$t('purchase.order.complete')"
          />
        </el-tabs>
        <el-table
          ref="imgTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <!-- 采购编号 -->
          <el-table-column
            prop="seq"
            :label="$t('purchase.order.purchaseNumber')"
          >
            <template #default="scope">
              <span>{{ scope.row.purchaseNumber }}</span>
            </template>
          </el-table-column>
          <!-- 物流编号 -->
          <el-table-column
            :label="$t('order.logisticsNumber')"
          >
            <template #default="scope">
              <span>{{ scope.row.dvyFlowId || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 供应商 -->
          <el-table-column
            :label="$t('product.supplier')"
          >
            <template #default="scope">
              <span>{{ scope.row.supplierName }}</span>
            </template>
          </el-table-column>
          <!-- 采购金额 -->
          <el-table-column
            prop="imgType"
            :label="$t('purchase.order.purchaseAmount')"
          >
            <template #default="scope">
              <span>{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <!-- 采购数量 -->
          <el-table-column
            prop="imgType"
            :label="$t('purchase.order.purchaseNum')"
          >
            <template #default="scope">
              <span>{{ scope.row.totalStock }}</span>
            </template>
          </el-table-column>
          <!-- 送达日期 -->
          <el-table-column
            prop="imgType"
            class-name="deliver-time"
            :label="$t('purchase.order.deliverTime')"
          >
            <template #default="scope">
              <span>{{ scope.row.deliverTime&&scope.row.deliverTime.substring(0,10) }}</span>
            </template>
          </el-table-column>
          <!-- 状态 -->
          <el-table-column
            prop="imgType"
            :label="$t('publics.status')"
          >
            <template #default="scope">
              <span v-if="scope.row.status === 0">{{ $t('purchase.order.voided') }}</span>
              <span v-if="scope.row.status === 1">{{ $t('purchase.order.warehoused') }}</span>
              <span v-if="scope.row.status === 2">{{ $t('purchase.order.partiallyComplete') }}</span>
              <span v-if="scope.row.status === 3">{{ $t('purchase.order.complete') }}</span>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="( scope.row.status === 1 || scope.row.status === 2 ) && isAuth('purchase:purchaseOrder:inbound')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.purchaseOrderId)"
                >
                  {{ $t('purchase.order.inbound') }}
                </div>
                <div
                  v-if="scope.row.status === 1 && isAuth('purchase:purchaseOrder:nullify')"
                  class="default-btn text-btn"
                  @click="nullifyHandle(scope.row.purchaseOrderId)"
                >
                  {{ $t('purchase.order.nullify') }}
                </div>
                <div
                  v-if="scope.row.status === 2 && isAuth('purchase:purchaseOrder:complete')"
                  class="default-btn text-btn"
                  @click="completeHandle(scope.row.purchaseOrderId)"
                >
                  {{ $t('purchase.order.finish') }}
                </div>
                <div
                  v-if="isAuth('purchase:purchaseOrder:info')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.purchaseOrderId, true)"
                >
                  {{ $t('shop.withdrawalDetail') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
  </div>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'

let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const dataForm = reactive({})
let sts = 0
const status = ref(-1)
let isSubmit = false
const params = reactive({
  supplierName: '',
  purchaseNumber: ''
})
const activeName = ref('0')
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

onActivated(() => {
  // 携带参数查询
  // const query = useRoute().query
  // getDataList(page, query)
})
onMounted(() => {
  // 携带参数查询
  getDataList(page, useRoute().query)
  isSubmit = false

  // 监听页面滚动
  window.addEventListener('scroll', scrollToTop)
})
onUnmounted(() => {
  // 页面销毁时移除监听
  window.removeEventListener('scroll', scrollToTop)
})

/**
 * 页面滚动事件
 */
const showHeadScroll = ref(null)
const scrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 400
}

/**
 * 获取数据列表
 */
const getDataList = (pageParam, newData = false) => {
  pageParam = (pageParam === undefined ? page : pageParam)
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(params))
  }
  http({
    url: http.adornUrl('/purchase/order/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize,
          status: status.value >= 0 ? status.value : null
        },
        tempSearchForm
      ), false
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    sts = status.value >= 0 ? status.value + 1 : 0
  })
}
// 新增 / 修改
const Router = useRouter()
const onAddOrUpdate = (id, view) => {
  Router.push({
    path: '/stock/purchases/order/new',
    query: {
      purchaseOrderId: id,
      view
    }
  })
}
// 作废
const nullifyHandle = (id) => {
  ElMessageBox.confirm(`${$t('purchase.order.determineCancellationPurchaseOrder')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    if (isSubmit) {
      return
    }
    isSubmit = true
    http({
      url: http.adornUrl('/purchase/order/nullify/' + id),
      method: 'delete'
    }).then(() => {
      getDataList(page)
      isSubmit = false
    }).catch(e => {
      isSubmit = false
    })
  })
}
// 完成
const completeHandle = (id) => {
  ElMessageBox.confirm(`${$t('purchase.order.finalizePurchaseOrder')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    if (isSubmit) {
      return
    }
    isSubmit = true
    http({
      url: http.adornUrl('/purchase/order/complete'),
      method: 'put',
      data: {
        purchaseOrderId: id
      }
    }).then(() => {
      getDataList(page)
      isSubmit = false
    }).catch(e => {
      isSubmit = false
    })
  })
}
// 每页数
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  getDataList(page)
}
// 当前页
const currentChangeHandle = (val) => {
  page.currentPage = val
  getDataList(page)
}
/**
 * 导航选择状态
 */
const selectNav = (e) => {
  const _sts = e.paneName
  activeName.value = _sts
  sts = parseInt(_sts)
  status.value = sts ? parseInt(sts) - 1 : null
  page.currentPage = 1
  getDataList(page)
}
// 清空按钮
const clear = () => {
  params.supplierName = ''
  params.purchaseNumber = ''
}
// 搜索查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

</script>
<style lang="scss" scoped>
.page-stock-purchases-order-list.main-container {
  :deep(.el-table__body) {
    .deliver-time {
      .cell {
        padding-left: 0;
        padding-right: 0;
      }
    }
  }
}
</style>
